﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Dynamic;
using Newtonsoft.Json;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Cart.Api;
namespace Cart.API.Controllers
{
    public class SignController : ApiController
    {
        [HttpGet]
        public dynamic SignIn(string loginname,string loginpwd)
        {
            //密钥
            string JwtKey = ConfigurationManager.AppSettings["JwtKey"];
            //过期周期
            string JwtExp =ConfigurationManager.AppSettings["JwtExp"];

            //过期时间
            var exp = string.IsNullOrWhiteSpace(JwtExp)?30:int.Parse(JwtExp);


            dynamic data = new ExpandoObject();

            if (ValidateUser(loginname,loginpwd))
            {
                AuthInfo info = new AuthInfo
                {
                    UserId = 1,
                    UserName = "Admin",
                    Roles = "管理员",             
                    Exp = DateTime.Now.AddMinutes(exp).Ticks
                };

                try
                {
                    //加密方式
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    //序列化方式
                    IJsonSerializer serializer = new JsonNetSerializer();
                    //编码方式
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    //声明Jwt
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                    //生成Token
                    var token = encoder.Encode(info, JwtKey);
                    info.Token = token;

                    data.msg = "登录成功";
                    data.data = info;
                    data.code = 1;
                }
                catch (Exception ex)
                {
                    data.msg = ex.Message;
                    data.code = -2;
                }

            }
            else
            {
                data.code = -1;
                data.msg = "账户或者密码错误！";
            }
            return data;

        }

        //校验用户名密码（正式环境中应该是数据库校验）
        private bool ValidateUser(string loginname, string loginpwd)
        {
            if (loginname == "admin" && loginpwd == "123")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}